<template>
  <div class="settings-container">
    <div class="dashboard-container">
      <div class="app-container">
        <el-card>
          <el-tabs>
            <!-- 放置页签 -->
            <el-tab-pane label="角色管理">
              <!-- 新增角色按钮 -->
              <el-row style="height:60px">
                <el-button icon="el-icon-plus" size="small" type="primary" @click="hAdd">新增角色</el-button>
              </el-row>
              <!-- 表格 -->
              <el-table :data="roles">
                <el-table-column type="index" label="序号" width="120" />
                <el-table-column prop="name" label="角色名称" width="240" />
                <el-table-column prop="description" label="描述" />
                <el-table-column label="操作">
                  <template v-slot="scope">
                    <el-button size="small" type="success" @click="hAssign(scope.row.id)">分配权限</el-button>
                    <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                    <!-- <span>{{ scope.row.id }}</span> -->
                  </template>
                </el-table-column>
              </el-table>


              <el-row type="flex" justify="center" align="middle" style="height: 60px">
                <!-- 分页组件 -->
                <el-pagination layout="prev,pager,next" :total="total" :page-size="q.pagesize" :current-page="q.page"
                  @current-change="hCurrentChange" />
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>

    <el-dialog :title="isEdit ? '编辑角色' : '新增角色'" :close-on-click-modal="false" :close-on-press-escape="false"
      :visible.sync="showDialog" @closed="hClose">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="hClose">取消</el-button>
          <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog title="分配权限" :close-on-click-modal="false" :close-on-press-escape="false"
      :visible.sync="showDialogAssign">
      <assign-permission v-if="showDialogAssign" :id="curId" @close="showDialogAssign = false"></assign-permission>

    </el-dialog>
  </div>
</template>

<script>
import { addRole, deleteRoleById, getRoles, updateRoleById } from '@/api/role';
import assignPermission from './assignPermission.vue';

export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roles: [],
      q: {
        page: 1,
        pagesize: 2
      },
      total: 0,
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
      },
      isEdit: false,
      showDialogAssign: false,
      curId: ''


    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    async loadRoles() {
      try {
        const res = await getRoles(this.q)
        // console.log(res);
        this.roles = res.data.rows
        this.total = res.data.total
      } catch (e) {
        console.log(e);
      }
    },
    // test(scope) {
    //   console.log('scope', scope);
    // }
    hCurrentChange(page) {
      console.log(page);
      this.q.page = page
      this.loadRoles()
    },
    hDel(id) {
      this.$confirm('真的要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await deleteRoleById(id)
            console.log(res);
            this.$message({
              type: 'success',
              message: res.message
            });
            // 2. 如果当前表格中只有一条，删除之后自动请求上一页数据
            // +   if (this.roles.length === 1 && this.q.page > 1) {
            //   +       this.q.page--
            //     +   }
            if (this.roles.length === 1 && this.q.page > 1) {
              this.q.page--
            }
            this.loadRoles()
          } catch (error) {
            this.$message({
              type: 'warn',
              message: error.message
            });
          }

        })
        .catch(() => {
          this.$message({
            type: 'success',
            message: '取消操作!'
          });
        })

    },
    async hSubmit() {
      // this.$refs.roleForm.validate(valid => {
      //   if (!valid) return
      //   addRole(this.roleForm).then(res => {
      //     console.log(res);
      //     this.loadRoles()
      //     this.$message.success(res.message)
      //     this.showDialog = false
      //   }).catch((e) => {
      //     this.$message.error(e.message);
      //   })

      // })
      const valid = await this.$refs.roleForm.validate().catch(e => e)
      if (!valid) return
      this.isEdit ? this.doEdit() : this.doAdd()


    },
    async doAdd() {
      const res = await addRole(this.roleForm).catch(e => {

        this.$message.error(e.message)
      })

      this.$message.success(res.message)
      this.showDialog = false
      if (this.total % this.q.pagesize === 0) {
        this.total++
      }
      this.q.page = Math.ceil(this.total / this.q.pagesize)
      console.log(this.total);
      console.log(this.q.page);
      this.loadRoles()
    },
    async doEdit() {
      const res = await updateRoleById(this.roleForm).catch(e => {

        this.$message.error(e.message)
      })

      this.$message.success(res.message)
      this.showDialog = false

      this.loadRoles()
    },
    hEdit(row) {
      this.showDialog = true
      this.isEdit = true
      this.roleForm = { ...row }
      // this.roleForm = JSON.parse(JSON.stringify(row))

    },
    hAdd() {
      this.showDialog = true
      this.isEdit = false

    },
    hClose() {
      this.roleForm = { // 表单数据项
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    async hAssign(id) {
      this.showDialogAssign = true
      this.curId = id
    }
  }
}
</script>

<style scoped lang='less'></style>>